// 记忆函数

const _ = require('lodash')

function getArea(r) { 
  console.log(r)
  return Math.PI * r * r
}

// let getAreaWithM = _.memoize(getArea)

// console.log(getAreaWithM(4));
// console.log(getAreaWithM(4));
// console.log(getAreaWithM(4));

// getArea只打印了1次 
// 4
// 50.26548245743669
// 50.26548245743669
// 50.26548245743669

// 模拟 memoize 

function memoize(fn) {
  let cache = {}

  return function () { 
    let key = JSON.stringify(arguments)
    cache[key] = cache[key] || fn.apply(fn, arguments) // fn.apply(this, arguments)  同理
    return cache[key]
  }
}


let getAreaWithM = memoize(getArea)

console.log(getAreaWithM(4));
console.log(getAreaWithM(4));
console.log(getAreaWithM(4));

// 4
// 50.26548245743669
// 50.26548245743669